package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Chat implements javax.jms.MessageListener{

	private TopicSession pubSession;
	private TopicPublisher publisher;
	private TopicConnection connection;
	private String username;
	
	public Chat(String topicFactory, String topicName, String username) throws NamingException, JMSException{
		
		InitialContext context = new InitialContext();
		TopicConnectionFactory conFactory = (TopicConnectionFactory)context.lookup(topicFactory);
		connection = conFactory.createTopicConnection();
		connection.start();
		
		pubSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		TopicSession subSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		
		Topic chatTopic = (Topic)context.lookup(topicName);
		
		publisher = pubSession.createPublisher(chatTopic);
		TopicSubscriber subscriber = subSession.createSubscriber(chatTopic, null, true);
		
		subscriber.setMessageListener(this);
		this.username = username;
	}
	
	@Override
	public void onMessage(Message message) {
		
		TextMessage textMessage = (TextMessage)message;
		try {
			System.out.println(textMessage.getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public void writeMessage(String text) throws JMSException{
		
		TextMessage message = pubSession.createTextMessage();
		message.setText(username + ":" + text);
		publisher.publish(message);
	}
	
	public void close(){
		
		try {
			connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws NamingException, JMSException, IOException {
		
//		String username = "涂有";
		String username = "杨瑞";
		Chat chat = new Chat("a", "b", username);
		System.out.println("欢迎你:" + username);
		
		BufferedReader commandLine = new BufferedReader(new InputStreamReader(System.in));
		
		while(true){
			
			String line = commandLine.readLine();
			if("line".equalsIgnoreCase("exit")){
				
				chat.close();
				System.exit(0);
			}else{
				
				chat.writeMessage(line);
			}
		}
	}
}
